﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using Blog.Models;
using BlogModel;

namespace Blog.Data
{
    public static class BloggRollRepository
    {
        public static List<BlogRollModel> GetAllBlogRolls()
        {
            var blogRolls =
                from b in DB.Context.BlogRollSet
                where !b.IsDeleted
                select new BlogRollModel
                {
                    BlogRollId = b.BlogRollId,
                    Title = b.Title,
                    Url = b.Url,
                    BlogId = b.BlogId
                };
            
            return blogRolls.ToList();
        }

        public static int InsertBlogRoll(BlogRollModel blogRollModel)
        {
            var blogRoll = new BlogRoll
            {
                Title = blogRollModel.Title,
                Url = blogRollModel.Url,
                BlogId = blogRollModel.BlogId
            };

            DB.Context.BlogRollSet.Add(blogRoll);
            DB.Context.SaveChanges();

            return blogRoll.BlogRollId;
        }

        public static BlogRollModel GetBlogRollById(int id)
        {
            var blogRoll = DB.Context.BlogRollSet
                .FirstOrDefault(b => b.BlogRollId == id && !b.IsDeleted);

            if (blogRoll == null)
                return null;
            
            return new BlogRollModel
            {
                BlogRollId = blogRoll.BlogId,
                BlogId = blogRoll.BlogId,
                Title = blogRoll.Title,
                Url = blogRoll.Url
            };

        }

        public static int UpdateBlogRoll(BlogRollModel blogRollModel)
        {
            var blogRoll = new BlogRoll
            {
                BlogRollId = blogRollModel.BlogRollId,
                Title = blogRollModel.Title,
                Url = blogRollModel.Url,
                BlogId = blogRollModel.BlogId
            };

            DB.Context.BlogRollSet.AddOrUpdate(b => b.BlogRollId, blogRoll);
            return DB.Context.SaveChanges();
        }

        public static int DeleteBloggRoll(int id)
        {
            var blogRoll = DB.Context.BlogRollSet
                .FirstOrDefault(b => b.BlogRollId == id);

            if (blogRoll != null)
                blogRoll.IsDeleted = true;

            return DB.Context.SaveChanges();
        }
    }
}